//
//  GoodsDetailViewController.m
//  TerritoryShopkeeper
//
//  Created by xiaowu on 2017/12/6.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "GoodsDetailViewController.h"
#import "TitleSelectionView.h"
#import "SliderBannerView.h"

#import "GoodCommentCell.h"
#import "GoodEvaluateModel.h"
#import "ImageUrlModel.h"
// view
#import "GoodsFlashSaleHeadView.h"
#import "CommentHeadView.h"
#import "GoodsDetailBottomView.h"
// cell
#import "GoodsTitleCell.h"
#import "GoodsDescriptionCell.h"
#import "GoodsPriceCell.h"
#import "GetTicketCell.h"
#import "PromotionCell.h"
#import "PostageCell.h"
#import "AttributeSelectCell.h"
#import "GoodsCreditsCell.h"
// model
#import "GoodDetailModel.h"
#import "ShopcartModel.h"
// tool
#import "GoodStandardView.h"
#import "SKUManager.h"
// VC
#import "CouponViewController.h"
#import "ShopcartOrderViewController.h"
#import "ShoppingCartHomeViewController.h"

#import "GoodsAttributePopView.h"
#import "LoginViewController.h"

@interface GoodsDetailViewController () <UIWebViewDelegate,UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate, SliderBannerViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

@property (nonatomic, strong) TitleSelectionView *titleView;

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UITableView *detailTableView;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UITableView *commenTableView;

@property (nonatomic, strong) SliderBannerView *sliderBannerView;
@property (nonatomic, strong) UIView *tableHeaderView;

@property (nonatomic, strong) GoodsTitleCell *titleCell;
@property (nonatomic, strong) GoodsDescriptionCell *descriptionCell;
@property (nonatomic, strong) GoodsPriceCell *priceCell;
@property (nonatomic, strong) GetTicketCell *ticketCell;
@property (nonatomic, strong) PromotionCell *promotionCell;
@property (nonatomic, strong) PostageCell *postageCell;
@property (nonatomic, strong) AttributeSelectCell *selectCell;
@property (nonatomic, strong) GoodsCreditsCell *creditsCell;

@property (nonatomic, strong) GoodsFlashSaleHeadView *flashSaleHeadView;

@property (nonatomic, strong) GoodsDetailBottomView *bottomView;

@property (nonatomic, strong) GoodDetailModel *detailModel;
// 刷新选中的属性
@property (nonatomic, strong) GoodsAttributePriceModel *responsePriceModel;
// 选中的属性
@property (nonatomic, strong) NSMutableArray *selectArr;

@property (nonatomic, strong) NSMutableArray *goodEvaluateListArr;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, copy) NSString *escore;
@property (nonatomic, copy) NSString *evaluate;

@property (nonatomic, strong) NSMutableArray<CouponModel *> *couponArray;
@property (nonatomic, strong) NSMutableArray<PromotionModel *> *promotionArray;
@end

@implementation GoodsDetailViewController

- (instancetype)init {
    self = [super init];
    if (self) {
        _titleCell = [[[NSBundle mainBundle] loadNibNamed:@"GoodsTitleCell" owner:self options:nil] firstObject];
        _descriptionCell = [[[NSBundle mainBundle] loadNibNamed:@"GoodsDescriptionCell" owner:self options:nil] firstObject];
        _priceCell = [[[NSBundle mainBundle] loadNibNamed:@"GoodsPriceCell" owner:self options:nil] firstObject];
        _ticketCell = [[[NSBundle mainBundle] loadNibNamed:@"GetTicketCell" owner:self options:nil] firstObject];
        _promotionCell = [[[NSBundle mainBundle] loadNibNamed:@"PromotionCell" owner:self options:nil] firstObject];
        _postageCell = [[[NSBundle mainBundle] loadNibNamed:@"PostageCell" owner:self options:nil] firstObject];
        _selectCell = [[[NSBundle mainBundle] loadNibNamed:@"AttributeSelectCell" owner:self options:nil] firstObject];
        _creditsCell = [[[NSBundle mainBundle] loadNibNamed:@"GoodsCreditsCell" owner:self options:nil] firstObject];
        _bottomView = [[GoodsDetailBottomView alloc] init];
        _gid = @"";
        _detailModel = [[GoodDetailModel alloc] init];
        _responsePriceModel = nil;
        _selectArr = [NSMutableArray array];
        _goodEvaluateListArr = [NSMutableArray array];
        _currentPage = 1;
        _escore = @"";
        _evaluate = @"";
        
        _type = GoodsDetailViewControllerTypeForNormal;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configure];
    [self configureUI];
    
    [self loadNetWork];
    [self responseBlock];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    CGFloat bottomHeight = 49;
    if (@available(iOS 11.0, *)) {
        NSLog(@"safeAreaLayoutGuide : %f",     self.view.safeAreaLayoutGuide.layoutFrame.size.height);
        bottomHeight = 55;// 49 + 34;
    } else {
        // Fallback on earlier versions
    }
    if (self.type == GoodsDetailViewControllerTypeForNearby) {
        bottomHeight = 0;
    }
    
    self.scrollView.frame = CGRectMake(0, 0, ScreenWidth, self.view.height - bottomHeight);

    
    self.detailTableView.frame = CGRectMake(0, 0, ScreenWidth, self.scrollView.height);
    self.webView.frame = CGRectMake(ScreenWidth, 0, ScreenWidth, self.scrollView.height);
    self.commenTableView.frame = CGRectMake(2 * ScreenWidth, 0, ScreenWidth, self.scrollView.height);
    
    self.scrollView.contentSize = CGSizeMake(ScreenWidth * 3, self.scrollView.height);
    
    self.bottomView.frame = CGRectMake(0, self.scrollView.bottom, ScreenWidth, bottomHeight);

}

#pragma mark - Method
- (void)configure {
    [self.navigationItem setTitleView:self.titleView];
    __weak typeof(self) weakSelf = self;
    self.titleView.block = ^(NSInteger index) {
        [weakSelf.scrollView scrollRectToVisible:CGRectMake(index * weakSelf.scrollView.width, 0, weakSelf.scrollView.width, weakSelf.scrollView.height) animated:YES];

        switch (index) {
            case 0: {
            } break;
            case 1: {
            } break;
            case 2: {
            } break;
            default:
                break;
        }
    };
    
    self.commenTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.currentPage = 1;
        [weakSelf getEvaluateList];
    }];
    self.commenTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.currentPage += 1;
        [weakSelf getEvaluateList];
    }];
    [self.commenTableView.mj_footer setHidden:YES];
}

- (void)configureUI {
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.detailTableView];
    [self.scrollView addSubview:self.webView];
    [self.scrollView addSubview:self.commenTableView];
    [self.view addSubview:self.bottomView];
}

- (void)configureTableHeader {
    
    NSMutableArray *itemArr = [NSMutableArray array];
    for (ImageUrlModel *model in self.detailModel.goodsimg) {
        SliderBannerItem *item = [SliderBannerItem initWithImageUrl:model.giimg andIsVideo:NO];
        [itemArr addObject:item];
    }
    
    for (UIView *view in self.tableHeaderView.subviews) {
        if ([view isKindOfClass:[SliderBannerView class]]) {
            [view removeFromSuperview];
        }
    }
    self.sliderBannerView = [[SliderBannerView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth)];
    [self.sliderBannerView setDataSource:itemArr withDelegate:self withPlaceHolder:PlaceholderImageBig infiniteLoop:YES];
    
    [self.tableHeaderView addSubview:self.sliderBannerView];
    self.tableHeaderView.frame = CGRectMake(0, 0, ScreenWidth, ScreenWidth);
    
    self.detailTableView.tableHeaderView = self.tableHeaderView;
    [self.detailTableView reloadData];
    
}

- (void)responseBlock {
    __weak typeof(self) weakSelf = self;
    self.bottomView.block = ^(NSInteger index) {
        switch (index) {
            case 0: {
                // 客服
                [weakSelf goToServiceChat];
            } break;
            case 1: {
                // 收藏
                if (weakSelf.detailModel.iscollection) {
                    [weakSelf cancelCollect];
                } else {
                    [weakSelf addToCollect];
                }
            } break;
            case 2: {
                // 购物车
                if (![weakSelf checkLogin]) {
                    return;
                }
                
                ShoppingCartHomeViewController *shopcartVC = [[ShoppingCartHomeViewController alloc] init];
                shopcartVC.type = 1;
                [weakSelf.navigationController pushViewController:shopcartVC animated:YES];
            } break;
            case 3: {
                GoodStandardViewType type = GoodStandardViewTypeForAddCart;
                if (weakSelf.type == GoodsDetailViewControllerTypeForGroup) {
                    //MARK:测试 单独买
                    NSLog(@"单独买");
                    type = GoodStandardViewTypeGroupAlone;
                }
                [GoodsAttributePopView showWithData:weakSelf.detailModel popType:GoodsAttributePopTypeAddCart actionCallback:^(id value) {
                    [weakSelf _popoDownActionWithData:value];
                }];
                // 加入购物车
//                [GoodStandardView showGoodStandardViewWithTitle:weakSelf.detailModel.gname
//                                                          price:weakSelf.detailModel.gprice
//                                                        pgprice:@""
//                                                          count:@"0"
//                                                       imageURL:weakSelf.detailModel.gimg
//                                          goodAttributeModelArr:weakSelf.detailModel.attribute
//                                    goodsAttributePriceModelArr:weakSelf.detailModel.goodsattribute
//                                                           type:type
//                                                      needReset:NO
//                                                          block:^(NSInteger buttonIndex, NSMutableArray *arr, GoodsAttributePriceModel *priceModel, NSString *count) {
//                                                              // 修改外面的原价和现价，以及选中的属性名字
//                                                              weakSelf.responsePriceModel = priceModel;
//                                                              weakSelf.selectArr = [NSMutableArray arrayWithArray:arr];
//                                                              [weakSelf.detailTableView reloadData];
//                                                              if (buttonIndex == 0 && type == GoodStandardViewTypeForAddCart) {
//                                                                  [weakSelf addToShopCart:count goodsAttributePriceModel:priceModel];
//                                                              } else if (buttonIndex == 1 && type == GoodStandardViewTypeGroupAlone) {
//                                                                  [weakSelf groupAlone:priceModel withCount:count];
//                                                              }
//                                                          }];
            } break;
            case 4: {
                GoodStandardViewType type = GoodStandardViewTypeForBuy;
                if (self.type == GoodsDetailViewControllerTypeForGroup) {
                    //MARK:测试 团购
                    NSLog(@"团购");
                    type = GoodStandardViewTypeGroup;
                }
                // 立即购买
//                [GoodStandardView showGoodStandardViewWithTitle:weakSelf.detailModel.gname
//                                                          price:weakSelf.detailModel.gprice
//                                                        pgprice:weakSelf.detailModel.pgprice
//                                                          count:@"0"
//                                                       imageURL:weakSelf.detailModel.gimg
//                                          goodAttributeModelArr:weakSelf.detailModel.attribute
//                                    goodsAttributePriceModelArr:weakSelf.detailModel.goodsattribute
//                                                           type:type
//                                                      needReset:NO
//                                                          block:^(NSInteger buttonIndex, NSMutableArray *arr, GoodsAttributePriceModel *priceModel, NSString *count) {
//                                                              // 修改外面的原价和现价，以及选中的属性名字
//                                                              weakSelf.responsePriceModel = priceModel;
//                                                              weakSelf.selectArr = [NSMutableArray arrayWithArray:arr];
//                                                              [weakSelf.detailTableView reloadData];
//                                                              if (buttonIndex == 1) {
//                                                                  if (type == GoodStandardViewTypeGroup) {
//                                                                      [weakSelf group:priceModel withCount:count];
//                                                                  } else {
//                                                                      [weakSelf jumpToBuy:priceModel withCount:count withTwoAttribute:arr];
//                                                                  }
//                                                              }
//                                                          }];
                [GoodsAttributePopView showWithData:weakSelf.detailModel popType:GoodsAttributePopTypeBuy actionCallback:^(id value) {
                    [weakSelf _popoDownActionWithData:value];
                }];
            } break;
            case 5:
            {
                //MARK:测试 积分商品立即购买
                NSLog(@"立即兑换");
                [GoodStandardView showGoodStandardViewWithTitle:weakSelf.detailModel.gname
                                                          price:weakSelf.detailModel.gintegral
                                                        pgprice:@""
                                                          count:@"0"
                                                       imageURL:weakSelf.detailModel.gimg
                                          goodAttributeModelArr:weakSelf.detailModel.attribute
                                    goodsAttributePriceModelArr:weakSelf.detailModel.goodsattribute
                                                           type:GoodStandardViewTypeIntegral
                                                      needReset:NO
                                                          block:^(NSInteger buttonIndex, NSMutableArray *arr, GoodsAttributePriceModel *priceModel, NSString *count) {
                                                              // 修改外面的原价和现价，以及选中的属性名字
                                                              weakSelf.responsePriceModel = priceModel;
                                                              weakSelf.selectArr = [NSMutableArray arrayWithArray:arr];
                                                              [weakSelf.detailTableView reloadData];
                                                              if (buttonIndex == 1) {
                                                                  [weakSelf integral:priceModel withCount:count];
                                                              }
                                                          }];
            } break;
            default:
                break;
        }
    };
}

//弹窗视图收起之后要处理的东西
- (void)_popoDownActionWithData:(id)data{
    NSInteger type = [[data safeNumberForKey:@"type"] integerValue];
    NSString *  count = [data safeStringForKey:@"count"];
    id price = [data safeObjectForKey:@"price"];
    id fields = [price safeObjectForKey:@"fields"];
    self.responsePriceModel = [[GoodsAttributePriceModel alloc] init];
    self.responsePriceModel.gaid = self.detailModel.gaid;
    if (type == 0) {//加入购车
        NSLog(@"加入购车");
        [self _addGoodsToCart:count fields:fields goodsAttributePriceModel:self.responsePriceModel];
    }else{         //立即购买
        NSLog(@"立即购买");
        [self _newjumpToBuy:self.responsePriceModel withCount:count withTwoAttribute:nil fields:fields];
    }
}

- (void)reloadUI {
    
    if (self.detailModel.isigoods) {
        // 判断是否是积分兑换的商品
        self.type = GoodsDetailViewControllerTypeForCredits;
    } else if (self.detailModel.gseckill) {
        // 判断是否限时秒杀商品
        self.type = GoodsDetailViewControllerTypeForFlashSale;
        CGFloat startMin = [DateSomeThing getStringWithCurrentTimeStr:self.detailModel.sktime currentDateFormat:@"HH:mm:ss"];
        CGFloat endMin = [DateSomeThing getStringWithCurrentTimeStr:self.detailModel.endtime currentDateFormat:@"HH:mm:ss"];
        CGFloat sec = 0;
        if ([self.detailModel.gstarttime isEqualToString:@"0"]) {
            if (startMin >= 0) {
                // 未开始
                self.type = GoodsDetailViewControllerTypeForNormal;
            } else if (startMin < 0 && endMin > 0) {
                // 抢购中
                sec = [DateSomeThing getStringWithCurrentTimeStr:self.detailModel.endtime currentDateFormat:@"HH:mm:ss"];
            } else if (endMin <= 0) {
                // 已结束
                self.type = GoodsDetailViewControllerTypeForNormal;
            }
            
        } else {
            NSString *start = [DateSomeThing getDateStrWithTimestampstr:self.detailModel.gstarttime formatStr:@"yyyy-MM-dd"];
            NSString *now = [DateSomeThing getDateStr:[NSDate date] dateFormat:@"yyyy-MM-dd"];
            if ([start isEqualToString:now]) {
                if (startMin >= 0) {
                    // 未开始
                    self.type = GoodsDetailViewControllerTypeForNormal;
                } else if (startMin < 0 && endMin > 0) {
                    // 抢购中
                    sec = [DateSomeThing getStringWithCurrentTimeStr:self.detailModel.endtime currentDateFormat:@"HH:mm:ss"];
                } else if (endMin <= 0) {
                    // 已结束
                    self.type = GoodsDetailViewControllerTypeForNormal;
                }
            } else {
                self.type = GoodsDetailViewControllerTypeForNormal;
            }
        }
        
        [self.flashSaleHeadView setValueWithPrice:self.detailModel.gseckillprice oldPrice:self.detailModel.goldprice saleCount:self.detailModel.salesvolume time:sec];
    } else if (self.detailModel.isgroupbuy) {
        // 判断是否是海外团购商品
        self.type = GoodsDetailViewControllerTypeForGroup;
    } else if (self.detailModel.ispurchasing) {
        // 判断是否是海外代购商品
        self.type = GoodsDetailViewControllerTypeForAbroad;
    } else if (TextIsNotNil(self.detailModel.sid) && ![self.detailModel.sid isEqualToString:@"0"]) {
        // 判断是否是 附近门店商品， 如果有店铺一定是附近门店的商品
        self.type = GoodsDetailViewControllerTypeForNearby;
    } else {
        self.type = GoodsDetailViewControllerTypeForNormal;
    }
    
    // 重置已选中的属性
    [self setSelectArrIfExist];
    // 把无库存的priceitem 去除
    self.detailModel.goodsattribute = [SKUManager getSKUCountPriceItem:self.detailModel.goodsattribute];

    [self.detailTableView reloadData];
    [self.commenTableView reloadData];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.detailModel.gdetails]]];
    
    if (self.type == GoodsDetailViewControllerTypeForNearby) {
        [self.bottomView setHidden:YES];
    } else {
        [self.bottomView setBottomValueWith:self.detailModel type:self.type];
    }
}

- (NSString *)getAllStandardName:(NSArray *)arr {
    NSString *str = @"";
    
    if (self.responsePriceModel) {
        for (GoodAttributeValueModel *model in self.selectArr) {
            str = [NSString stringWithFormat:@"%@%@ ", str, model.taname];
        }
        return str;
    }
    for (GoodAttributeModel *model in arr) {
        str = [NSString stringWithFormat:@"%@%@ ", str, model.ganame];
    }
    return str;
}

- (void)setSelectArrIfExist {
    if (self.selectArr.count > 0) {
        for (GoodAttributeModel *attributeModel in self.detailModel.attribute) {
            for (GoodAttributeValueModel *valueModel in attributeModel.twoattribute) {
                for (GoodAttributeValueModel *selectValueModel in self.selectArr) {
                    if ([valueModel.taid isEqualToString:selectValueModel.taid]) {
                        valueModel.isSelected = YES;
                    }
                }
            }
        }
    }
}

#pragma mark - NetWork
- (void)loadNetWork {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:self.gid forKey:@"gid"];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Goods_Detail parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSDictionary *data = [responseDic safeJsonObjectForKey:@"data"];
            
            weakSelf.detailModel = [GoodDetailModel mj_objectWithKeyValues:data];
            
            [weakSelf getFullCut];      // 获取满减
            [weakSelf getCouponData];   // 获取优惠券列表
            [weakSelf getEvaluateList]; // 获取评论列表
            [weakSelf reloadUI];
            [weakSelf configureTableHeader]; // 轮播图重置
        } else {
            [MBProgressHUD showError:weakSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
}
- (void)getFullCut {
    [self.promotionArray removeAllObjects];
    if (self.detailModel.fullcut.count > 0) {
        PromotionModel *model = [[PromotionModel alloc] init];
        model.label = @"满减";
        for (GoodsFullCut *tempModel in self.detailModel.fullcut) {
            NSString *info = [NSString stringWithFormat:@"满%@元减%@元",tempModel.fcfull,tempModel.fccut];
            if (tempModel == self.detailModel.fullcut.firstObject) {
                model.labelInfo = info;
            } else {
                model.labelInfo = [NSString stringWithFormat:@"%@,%@",model.labelInfo,info];
            }
        }
        
        PromotionModel *model1 = [[PromotionModel alloc] init];
        model1.label = @"限制";
        model1.labelInfo = @"此价格不与套餐优惠同时享受";
        
        [self.promotionArray addObject:model];
        [self.promotionArray addObject:model1];
    }
    
    [self.detailTableView reloadData];
}
- (void)getCouponData {
    [self.couponArray removeAllObjects];
    if (self.detailModel.isdiscount) {
        [self.couponArray addObjectsFromArray:self.detailModel.coupon];
    }
    [self.detailTableView reloadData];
    return;
    __block typeof(self) blockSelf = self;
    [MYAFNetworking POST:URL_Get_GoodsCoupon parameters:@{@"gtrcid":self.detailModel.gtrcid,@"pageNumber":@"1",@"pageSize":@"10000"} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            NSArray *dataArr = responseObject[@"data"][@"list"];
            [blockSelf.couponArray removeAllObjects];
            for (NSDictionary *dic in dataArr) {
                [blockSelf.couponArray addObject:[CouponModel mj_objectWithKeyValues:dic]];
            }
            [blockSelf.detailTableView reloadData];
        } else {
            [MBProgressHUD showError:blockSelf.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD showError:blockSelf.view title:@"" code:@"" animated:YES];
    }];
}

- (void)getEvaluateList {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:self.detailModel.gid forKey:@"gid"];
    [parameters safeSetObject:@(self.currentPage) forKey:@"pageNumber"];
    [parameters safeSetObject:PageSize forKey:@"pageSize"];
    
    __weak typeof(self) weakSelf = self;
    //    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Get_Evaluate parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [weakSelf.commenTableView.mj_header endRefreshing];
        [weakSelf.commenTableView.mj_footer endRefreshing];
        
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            NSDictionary *data = [responseDic safeJsonObjectForKey:@"data"];
            weakSelf.escore = [responseDic safeJsonObjectForKey:@"escore"];
            weakSelf.evaluate = [responseDic safeJsonObjectForKey:@"evaluate"];
            NSArray *list = [data safeJsonObjectForKey:@"list"];
            NSString *totalPage = [data safeJsonObjectForKey:@"totalPage"];
            
            if (weakSelf.currentPage == totalPage.integerValue || totalPage.integerValue == 0) {
                [weakSelf.commenTableView.mj_footer endRefreshingWithNoMoreData];
                [weakSelf.commenTableView.mj_footer setHidden:YES];
            } else {
                [weakSelf.commenTableView.mj_footer resetNoMoreData];
                [weakSelf.commenTableView.mj_footer setHidden:NO];
            }
            
            if (weakSelf.currentPage== 1) {
                [weakSelf.goodEvaluateListArr removeAllObjects];
            }
            
            for (NSDictionary *modelDic in list) {
                GoodEvaluateModel *model = [GoodEvaluateModel mj_objectWithKeyValues:modelDic];
                [weakSelf.goodEvaluateListArr addObject:model];
            }
            [weakSelf reloadUI];
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:nil animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [weakSelf.commenTableView.mj_header endRefreshing];
        [weakSelf.commenTableView.mj_footer endRefreshing];
    } isNeedCache:NO];
    
}
// 单独买
- (void)groupAlone:(GoodsAttributePriceModel *)priceModel withCount:(NSString *)count {
    if (![self checkLogin]) {
        return;
    }
    
    self.detailModel.gaid = priceModel.gaid;
    self.detailModel.number = count;
    
    ShopcartOrderViewController *shopcartVC = [[ShopcartOrderViewController alloc] init];
    shopcartVC.isHaveWorldwide = YES;
    shopcartVC.type = ShopcartOrderTypeGoods;
    ShopcartModel *model = [ShopcartModel mj_objectWithKeyValues:self.detailModel];
    ShopcartClassifyModel *classifyModel = [ShopcartClassifyModel mj_objectWithKeyValues:@{@"shopcart":@[model],@"fullcut":@[]}];
    shopcartVC.tableArray = [[NSMutableArray alloc] initWithObjects:classifyModel, nil];
    [self.navigationController pushViewController:shopcartVC animated:YES];
}
// 团购
- (void)group:(GoodsAttributePriceModel *)priceModel withCount:(NSString *)count {
    if (![self checkLogin]) {
        return;
    }
    
    self.detailModel.gaid = priceModel.gaid;
    self.detailModel.number = count;
    
    ShopcartOrderViewController *shopcartVC = [[ShopcartOrderViewController alloc] init];
    shopcartVC.isHaveWorldwide = YES;
    shopcartVC.type = ShopcartOrderTypeGroup;
    ShopcartModel *model = [ShopcartModel mj_objectWithKeyValues:self.detailModel];
    ShopcartClassifyModel *classifyModel = [ShopcartClassifyModel mj_objectWithKeyValues:@{@"shopcart":@[model]}];
    shopcartVC.tableArray = [[NSMutableArray alloc] initWithObjects:classifyModel, nil];
    [self.navigationController pushViewController:shopcartVC animated:YES];
}
// 积分兑换
- (void)integral:(GoodsAttributePriceModel *)priceModel withCount:(NSString *)count {
    if (![self checkLogin]) {
        return;
    }
    
    self.detailModel.gaid = priceModel.gaid;
    self.detailModel.number = count;
    
    ShopcartOrderViewController *shopcartVC = [[ShopcartOrderViewController alloc] init];
    shopcartVC.isHaveWorldwide = NO;
    shopcartVC.type = ShopcartOrderTypeIntegral;
    ShopcartModel *model = [ShopcartModel mj_objectWithKeyValues:self.detailModel];
    ShopcartClassifyModel *classifyModel = [ShopcartClassifyModel mj_objectWithKeyValues:@{@"shopcart":@[model]}];
    shopcartVC.tableArray = [[NSMutableArray alloc] initWithObjects:classifyModel, nil];
    [self.navigationController pushViewController:shopcartVC animated:YES];
}
//新的加入购物车
- (void)_addGoodsToCart:(NSString *)count fields:(id)fields goodsAttributePriceModel:(GoodsAttributePriceModel *)priceModel{
    if (![self checkLogin]) {
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:self.detailModel.gid forKey:@"gid"];
    if (self.detailModel.goodsattribute.count > 0) {
        [parameters safeSetObject:self.detailModel.goodsattribute[0].gaid forKey:@"gaid"];
    }
    [parameters safeSetObject:count forKey:@"number"];
    [parameters safeSetObject:fields forKey:@"fields"];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Add_Shopcart parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            //MARK:忘了为什么要再调一遍刷详情接口
            //[weakSelf loadNetWork];
            [MBProgressHUD myShowHUDAddedTo:weakSelf.view labelText:@"加入购物车成功~" animated:YES];
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:code animated:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];

}
// 加入购物车
- (void)addToShopCart:(NSString *)count goodsAttributePriceModel:(GoodsAttributePriceModel *)priceModel {
    if (![self checkLogin]) {
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:self.detailModel.gid forKey:@"gid"];
    [parameters safeSetObject:priceModel.gaid forKey:@"gaid"];
    //[parameters safeSetObject:@"" forKey:@"devicecode"];
    [parameters safeSetObject:count forKey:@"number"];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Add_Shopcart parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            //MARK:忘了为什么要再调一遍刷详情接口
            //[weakSelf loadNetWork];
            [MBProgressHUD myShowHUDAddedTo:weakSelf.view labelText:@"加入购物车成功~" animated:YES];
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:code animated:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];
}

//新的修改 跳转到购买
- (void)_newjumpToBuy:(GoodsAttributePriceModel *)priceModel withCount:(NSString *)count withTwoAttribute:(NSMutableArray <GoodAttributeValueModel *> *)twoAttribute fields:(id)fields{
    if (![self checkLogin]) {
        return;
    }
    
    self.detailModel.gaid = priceModel.gaid;
    self.detailModel.number = count;
    
    NSString * gaid = @"";
    
    if (self.detailModel.goodsattribute.count > 0) {
        gaid =  self.detailModel.goodsattribute[0].gaid;
    }
    
    ShopcartModel *model = [ShopcartModel mj_objectWithKeyValues:self.detailModel];
    model.gaid = gaid;
    ShopcartClassifyModel *classifyModel;
    
    ShopcartOrderViewController *orderVC = [[ShopcartOrderViewController alloc] init];
    orderVC.isHaveWorldwide = self.detailModel.isabroad;
    
    //orderVC.priceAttStr = [NSString stringWithFormat:@"%.2f",priceModel.gaprice.floatValue * count.integerValue];
    
    switch (self.type) {
        case GoodsDetailViewControllerTypeForNormal:
            orderVC.type = ShopcartOrderTypeGoods;
            classifyModel = [ShopcartClassifyModel mj_objectWithKeyValues:@{@"shopcart":@[model],@"fullcut":@[]}];
            break;
        case GoodsDetailViewControllerTypeForFlashSale:
            orderVC.type = ShopcartOrderTypeSeckill;
            classifyModel = [ShopcartClassifyModel mj_objectWithKeyValues:@{@"shopcart":@[model]}];
            break;
        case GoodsDetailViewControllerTypeForAbroad:
            orderVC.type = ShopcartOrderTypePurchase;
            orderVC.isHaveWorldwide = YES;
            classifyModel = [ShopcartClassifyModel mj_objectWithKeyValues:@{@"shopcart":@[model]}];
            break;
        case GoodsDetailViewControllerTypeForGroup:
            orderVC.type = ShopcartOrderTypeGroup;
            orderVC.isHaveWorldwide = YES;
            classifyModel = [ShopcartClassifyModel mj_objectWithKeyValues:@{@"shopcart":@[model]}];
            break;
        case GoodsDetailViewControllerTypeForNearby:
            orderVC.type = ShopcartOrderTypeNearby;
            classifyModel = [ShopcartClassifyModel mj_objectWithKeyValues:@{@"shopcart":@[model]}];
            break;
        default:
            break;
    }
    orderVC.tableArray = [[NSMutableArray alloc] initWithObjects:classifyModel, nil];
    orderVC.fields = fields;
    [self.navigationController pushViewController:orderVC animated:YES];
}
// 跳转到 购买
- (void)jumpToBuy:(GoodsAttributePriceModel *)priceModel withCount:(NSString *)count withTwoAttribute:(NSMutableArray <GoodAttributeValueModel *> *)twoAttribute {
    
    if (![self checkLogin]) {
        return;
    }
    
    self.detailModel.gaid = priceModel.gaid;
    self.detailModel.number = count;
    
    ShopcartModel *model = [ShopcartModel mj_objectWithKeyValues:self.detailModel];
    ShopcartClassifyModel *classifyModel;
    
    ShopcartOrderViewController *orderVC = [[ShopcartOrderViewController alloc] init];
    orderVC.isHaveWorldwide = self.detailModel.isabroad;
    
    //orderVC.priceAttStr = [NSString stringWithFormat:@"%.2f",priceModel.gaprice.floatValue * count.integerValue];
    
    switch (self.type) {
        case GoodsDetailViewControllerTypeForNormal:
            orderVC.type = ShopcartOrderTypeGoods;
            classifyModel = [ShopcartClassifyModel mj_objectWithKeyValues:@{@"shopcart":@[model],@"fullcut":@[]}];
            break;
        case GoodsDetailViewControllerTypeForFlashSale:
            orderVC.type = ShopcartOrderTypeSeckill;
            classifyModel = [ShopcartClassifyModel mj_objectWithKeyValues:@{@"shopcart":@[model]}];
            break;
        case GoodsDetailViewControllerTypeForAbroad:
            orderVC.type = ShopcartOrderTypePurchase;
            orderVC.isHaveWorldwide = YES;
            classifyModel = [ShopcartClassifyModel mj_objectWithKeyValues:@{@"shopcart":@[model]}];
            break;
        case GoodsDetailViewControllerTypeForGroup:
            orderVC.type = ShopcartOrderTypeGroup;
            orderVC.isHaveWorldwide = YES;
            classifyModel = [ShopcartClassifyModel mj_objectWithKeyValues:@{@"shopcart":@[model]}];
            break;
        case GoodsDetailViewControllerTypeForNearby:
            orderVC.type = ShopcartOrderTypeNearby;
            classifyModel = [ShopcartClassifyModel mj_objectWithKeyValues:@{@"shopcart":@[model]}];
            break;
        default:
            break;
    }
    orderVC.tableArray = [[NSMutableArray alloc] initWithObjects:classifyModel, nil];
    [self.navigationController pushViewController:orderVC animated:YES];
}

- (void)addToCollect {
    if (![self checkLogin]) {
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:self.detailModel.gid forKey:@"gid"];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Save_Collect parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            self.detailModel.iscollection = YES;
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:code animated:YES];
        }
        [weakSelf reloadUI];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];
}

- (void)cancelCollect {
    if (![self checkLogin]) {
        return;
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:self.detailModel.gid forKey:@"gid"];
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Cancel_Collect parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeStringForKey:@"code"];
        if (code && [code isEqualToString:@"200"]) {
            self.detailModel.iscollection = NO;
        } else {
            [MBProgressHUD showError:weakSelf.view title:[responseDic safeStringForKey:@"message"] code:code animated:YES];
        }
        [weakSelf reloadUI];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.detailTableView) {
        return 2;
    } else if (tableView == self.commenTableView) {
        return 1;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.detailTableView) {
        if (section == 0) {
           
            switch (self.type) {
                case GoodsDetailViewControllerTypeForNormal: case GoodsDetailViewControllerTypeForAbroad: case GoodsDetailViewControllerTypeForGroup: {
                    return 7;
                } break;
                case GoodsDetailViewControllerTypeForCredits: {
                    return 5;
                } break;
                case GoodsDetailViewControllerTypeForFlashSale: {
                    return 6;
                } break;
                case GoodsDetailViewControllerTypeForNearby: {
                    return 4;
                } break;
                    
                default:
                    break;
            }
        } else {
            if (self.goodEvaluateListArr.count > 3) {
                return 3;
            } else {
                return self.goodEvaluateListArr.count;
            }
        }
    } else if (tableView == self.commenTableView) {
        return self.goodEvaluateListArr.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.detailTableView) {
        if (indexPath.section == 0) {
            if (indexPath.row == 0) {
                NSString *nameStr;
                if (self.detailModel.isnew) {
                    nameStr = [NSString stringWithFormat:@"       %@", self.detailModel.gname];
                } else {
                    nameStr = self.detailModel.gname;
                }
                [self.titleCell setValueForTitleCell:nameStr andLabel:(self.detailModel.isnew ? @" 新品 " : @"")];
                return self.titleCell;
            } else if (indexPath.row == 1) {
                self.descriptionCell.descriptionLabel.text = self.detailModel.gextension;
                return self.descriptionCell;
            }
            
            
            switch (self.type) {
                case GoodsDetailViewControllerTypeForNormal: case GoodsDetailViewControllerTypeForAbroad: case GoodsDetailViewControllerTypeForGroup: {
                    if (indexPath.row == 2) {
                        [self.priceCell setValueForCellWithPrice:self.detailModel.gprice notice:@" 降价通知 " oldPrice:self.detailModel.goldprice saleCount:self.detailModel.salesvolume];
                        __weak typeof(self) weakSelf = self;
                        self.priceCell.noticeBlock = ^{
                            [weakSelf clickedJJTZ];
                        };
                        return self.priceCell;
                    } else if (indexPath.row == 3) {
                        self.ticketCell.titleLabel.text = @"领券";
                        [self.ticketCell setTicketValueWith:self.couponArray];
                        return self.ticketCell;
                    } else if (indexPath.row == 4) {
                        self.promotionCell.titleLabel.text = @"优惠";
                        [self.promotionCell setValueForCellWithValue:self.promotionArray];
                        
                        return self.promotionCell;
                    } else if (indexPath.row == 5) {
                        self.postageCell.subTitleLabel.text = self.detailModel.isfreeshipping?@"包邮":@"不包邮";
                        return self.postageCell;
                    } else if (indexPath.row == 6) {
                        self.selectCell.titleLabel.text = @"请选择";
                        self.selectCell.subtitleLabel.text = [self getAllStandardName:self.detailModel.attribute];
                        //self.selectCell.contentLabel.text = ;// @"颜色,型号";
                        return self.selectCell;
                    }
                    
                    
                } break;
                case GoodsDetailViewControllerTypeForCredits: {
                    if (indexPath.row == 2) {
                        [self.creditsCell setValueForCell:self.detailModel.gintegral count:self.detailModel.salesvolume];
                        
                        return self.creditsCell;
                    } else if (indexPath.row == 3) {
                        self.postageCell.subTitleLabel.text = self.detailModel.isfreeshipping?@"包邮":@"不包邮";
                        return self.postageCell;
                    } else if (indexPath.row == 4) {
                        self.selectCell.titleLabel.text = @"请选择";
                        self.selectCell.subtitleLabel.text = [self getAllStandardName:self.detailModel.attribute];
                        return self.selectCell;
                    }
                } break;
                case GoodsDetailViewControllerTypeForFlashSale: {
                    if (indexPath.row == 2) {
                        self.ticketCell.titleLabel.text = @"领券";
                        [self.ticketCell setTicketValueWith:self.couponArray];
                        return self.ticketCell;
                    } else if (indexPath.row == 3) {
                        self.promotionCell.titleLabel.text = @"促销";
                        [self.promotionCell setValueForCellWithValue:self.promotionArray];
                        
                        return self.promotionCell;
                    } else if (indexPath.row == 4) {
                        self.postageCell.subTitleLabel.text = self.detailModel.isfreeshipping?@"包邮":@"不包邮";
                        return self.postageCell;
                    } else if (indexPath.row == 5) {
                        self.selectCell.titleLabel.text = @"请选择";
                        self.selectCell.subtitleLabel.text = [self getAllStandardName:self.detailModel.attribute];
                        return self.selectCell;
                    }
                    
                } break;
                case GoodsDetailViewControllerTypeForNearby: {
                    if (indexPath.row == 2) {
                        [self.priceCell setValueForCellWithPrice:self.detailModel.gprice notice:@" 降价通知 " oldPrice:self.detailModel.goldprice saleCount:self.detailModel.salesvolume];
                        self.priceCell.noticeButton.hidden = YES;
                        return self.priceCell;
                    } else if (indexPath.row == 3) {
                        self.postageCell.subTitleLabel.text = self.detailModel.isfreeshipping?@"包邮":@"不包邮";
                        return self.postageCell;
                    }
//                    else if (indexPath.row == 4) {
//                        self.selectCell.titleLabel.text = @"请选择";
//                        self.selectCell.subtitleLabel.text = [self getAllStandardName:self.detailModel.attribute];
//                        return self.selectCell;
//                    }
                } break;
                    
                default:
                    break;
            }
        } else {
            __weak typeof(self) weakSelf = self;
            GoodCommentCell *commentCell = [tableView dequeueReusableCellWithIdentifier:@"commentCell" forIndexPath:indexPath];
            GoodEvaluateModel *model = [self.goodEvaluateListArr objectAtIndex:indexPath.row];
            [commentCell setValueForCellWithContent:model.econtent headUrl:model.mimg time:model.createtime nickNamek:model.mnickname point:model.escore withImages:[model getEvaluateImgsUrl]];
            commentCell.picturesCell.block = ^(UIImageView *imageView, NSInteger index) {
                [weakSelf showPicture:imageView index:index urls:[model getEvaluateImgsUrl]];
            };
            return commentCell;
        }
    } else if (tableView == self.commenTableView) {
        __weak typeof(self) weakSelf = self;
        GoodCommentCell *commentCell = [tableView dequeueReusableCellWithIdentifier:@"commentCell" forIndexPath:indexPath];
        GoodEvaluateModel *model = [self.goodEvaluateListArr objectAtIndex:indexPath.row];
        [commentCell setValueForCellWithContent:model.econtent headUrl:model.mimg time:model.createtime nickNamek:model.mnickname point:model.escore withImages:[model getEvaluateImgsUrl]];
        commentCell.picturesCell.block = ^(UIImageView *imageView, NSInteger index) {
            [weakSelf showPicture:imageView index:index urls:[model getEvaluateImgsUrl]];
        };
        return commentCell;
    }
    
    return [[UITableViewCell alloc] init];
}

#pragma mark - 点击降价通知
- (void)clickedJJTZ{
    NSLog(@"点击降价通知");
    if ([UserInfo shareInstance].isLogin) {
        id pars = @{@"token":[UserInfo shareInstance].user.token,
                    @"gid":self.detailModel.gid,
                    @"price":self.detailModel.gprice
                    };
        __weak typeof(self) weakSelf = self;
        [MYAFNetworking POST:@"api2/setCutPrice" parameters:pars success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
            [MBProgressHUD showError:weakSelf.view title:[responseObject safeStringForKey:@"message"] code:nil animated:YES];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
            
        }];
    }else{
        LoginViewController *loginVC = [[LoginViewController alloc] init];
        BaseNavigationViewController *nav = [[BaseNavigationViewController alloc] initWithRootViewController:loginVC];
        [self presentViewController:nav animated:YES completion:nil];
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (tableView == self.detailTableView) {
        if (indexPath.section == 0) {
            switch (self.type) {
                case GoodsDetailViewControllerTypeForNormal: case GoodsDetailViewControllerTypeForAbroad: case GoodsDetailViewControllerTypeForGroup:
                {
                    if (indexPath.row == 3) {
                        return [GetTicketCell getHeight:self.couponArray];
                    }
                    if (indexPath.row == 4) {
                        return [PromotionCell getHeight:self.promotionArray];
                    }
                } break;
                case GoodsDetailViewControllerTypeForFlashSale:
                {
                    if (indexPath.row == 2) {
                        return [GetTicketCell getHeight:self.couponArray];
                    }
                    if (indexPath.row == 3) {
                        return [PromotionCell getHeight:self.promotionArray];
                    }
                } break;
                default:
                    break;
            }
        } else {
            GoodEvaluateModel *model = [self.goodEvaluateListArr objectAtIndex:indexPath.row];
            return [GoodCommentCell getHeightWithContent:model.econtent withImages:[model getEvaluateImgsUrl]];
        }
    } else if (tableView == self.commenTableView) {
        GoodEvaluateModel *model =  [self.goodEvaluateListArr safeObjectAtIndex:indexPath.row];
        return [GoodCommentCell getHeightWithContent:model.econtent withImages:[model getEvaluateImgsUrl]];
    }
    return UITableViewAutomaticDimension;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (tableView == self.detailTableView) {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor backgroundColor];
        return view;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (tableView == self.detailTableView) {
        return 10;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView == self.detailTableView) {
        if (section == 0) {
            if (self.type == GoodsDetailViewControllerTypeForFlashSale) {
                return self.flashSaleHeadView;
            }
        } else {
            CommentHeadView *headView =  [[CommentHeadView alloc] init];
            [headView setCommentHeadViewForTitle:[NSString stringWithFormat:@"用户评价(%@)", self.evaluate] percent:[NSString stringWithFormat:@"%@%%", self.escore] percentTitle:@"好评率"];
            return headView;
        }
    } else if (tableView == self.commenTableView) {
        CommentHeadView *headView =  [[CommentHeadView alloc] init];
        headView.titleLabelLLayout.constant = 19;
        headView.percentLabelRLayout.constant = 18;
        [headView.arrowImageView setHidden:YES];
        [headView setCommentHeadViewForTitle:[NSString stringWithFormat:@"用户评价(%@)", self.evaluate] percent:[NSString stringWithFormat:@"%@%%", self.escore] percentTitle:@"好评率"];
        
        return headView;
    }
    
    return [[UIView alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == self.detailTableView) {
        if (section == 0) {
            if (self.type == GoodsDetailViewControllerTypeForFlashSale) {
                return 50;
            }
        } else {
            return 44;
        }
    } else if (tableView == self.commenTableView) {
        return 44;
    }
    
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView == self.detailTableView) {
        if (indexPath.section == 0) {
            if (self.type == GoodsDetailViewControllerTypeForFlashSale) {
                if (indexPath.row == 2) {
                    [self selectCoupoonCell];
                }
                if (indexPath.row == 5) {
                    [self selectAttributeCell];
                }
            } else if (self.type == GoodsDetailViewControllerTypeForNormal || self.type == GoodsDetailViewControllerTypeForAbroad || self.type == GoodsDetailViewControllerTypeForGroup) {
                if (indexPath.row == 3) {
                    [self selectCoupoonCell];
                }
                if (indexPath.row == 6) {
                    [self selectAttributeCell];
                }
            } else if (self.type == GoodsDetailViewControllerTypeForCredits) {
                if (indexPath.row == 4) {
                    [self selectAttributeCell];
                }
            } else if (self.type == GoodsDetailViewControllerTypeForNearby) {
                if (indexPath.row == 4) {
                    [self selectAttributeCell];
                }
            }
        }
    }
}
- (void)selectCoupoonCell {
    if (![self checkLogin]) {
        return;
    }
    CouponViewController *couponVC = [[CouponViewController alloc] init];
    couponVC.type = CouponFromTypeGoodsDetail;
    couponVC.ids = self.detailModel.gtrcid;
    couponVC.number = @"10000";
    [self.navigationController pushViewController:couponVC animated:YES];
}
- (void)selectAttributeCell {
    __weak typeof(self) weakSelf = self;
    NSString *priceStr;
    GoodStandardViewType type;
    switch (self.type) {
        case GoodsDetailViewControllerTypeForGroup:
            priceStr = weakSelf.detailModel.gprice;
            type = GoodStandardViewTypeGroupAll;
            break;
        case GoodsDetailViewControllerTypeForCredits:
            priceStr = weakSelf.detailModel.gintegral;
            type = GoodStandardViewTypeIntegral;
            break;
        default:
            priceStr = weakSelf.detailModel.gprice;
            type = GoodStandardViewTypeForAll;
            break;
    }
    
//    [GoodStandardView showGoodStandardViewWithTitle:weakSelf.detailModel.gname
//                                              price:priceStr
//                                            pgprice:weakSelf.detailModel.pgprice
//                                              count:@"0"
//                                           imageURL:weakSelf.detailModel.gimg
//                              goodAttributeModelArr:weakSelf.detailModel.attribute
//                        goodsAttributePriceModelArr:weakSelf.detailModel.goodsattribute
//                                               type:type
//                                          needReset:NO
//                                              block:^(NSInteger buttonIndex, NSMutableArray *arr, GoodsAttributePriceModel *priceModel, NSString *count) {
//                                                  // 修改外面的原价和现价，以及选中的属性名字
//                                                  weakSelf.responsePriceModel = priceModel;
//                                                  weakSelf.selectArr = [NSMutableArray arrayWithArray:arr];
//                                                  [weakSelf.detailTableView reloadData];
//                                                  switch (type) {
//                                                      case GoodStandardViewTypeForAll:
//                                                      {
//                                                          if (buttonIndex == 0) {
//                                                              [weakSelf addToShopCart:count goodsAttributePriceModel:priceModel];
//                                                          } else if (buttonIndex == 1) {
//                                                              [weakSelf jumpToBuy:priceModel withCount:count withTwoAttribute:arr];
//                                                          }
//                                                      } break;
//                                                      case GoodStandardViewTypeGroupAll:
//                                                      {
//                                                          if (buttonIndex == 0) {
//                                                              [weakSelf groupAlone:priceModel withCount:count];
//                                                          } else if (buttonIndex == 1) {
//                                                              [weakSelf group:priceModel withCount:count];
//                                                          }
//                                                      } break;
//                                                      case GoodStandardViewTypeIntegral:
//                                                      {
//                                                          if (buttonIndex == 1) {
//                                                              [weakSelf integral:priceModel withCount:count];
//                                                          }
//                                                      } break;
//                                                      default:
//                                                          break;
//                                                  }
//
//                                              }];
    [GoodsAttributePopView showWithData:self.detailModel popType:GoodsAttributePopTypeCommon actionCallback:^(id value) {
        [weakSelf _popoDownActionWithData:value];
    }];
}
#pragma mark - DZNEmptyDataSetSource, DZNEmptyDataSetDelegate
//主提示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    if (scrollView == self.commenTableView) {
        return [[NSAttributedString alloc] initWithString:@"暂无评论"
                                               attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:16.0],
                                                            NSForegroundColorAttributeName:[UIColor grayTextColor]}];
    }
    return [[NSAttributedString alloc] init];
}
- (void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    if (scrollView == self.commenTableView) {
        [MBProgressHUD showHUDProgress:self.view animated:YES];
        [self getEvaluateList];
    }
}
#pragma mstk - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView != self.scrollView) {
        return;
    }
    CGFloat x = scrollView.contentOffset.x;
    CGFloat page = x / self.view.width;
    NSInteger index = (page + 0.3) / 1;
    
    [self.titleView animationForLine:index];
}

#pragma mark - UIWebViewDelegate
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *meta = [NSString stringWithFormat:@"document.getElementsByName(\"viewport\")[0].content = \"width=%f, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"", webView.frame.size.width];
    [webView stringByEvaluatingJavaScriptFromString:meta];
}

#pragma mark - getters
- (TitleSelectionView *)titleView {
    if (!_titleView) {
        _titleView = [[TitleSelectionView alloc] init];
        _titleView.size = CGSizeMake(171, 44);
        [_titleView setTitleWithArrs:@[@"商品",@"详情",@"评价"] withShowIndex:0 lineWidth:32];
    }
    return _titleView;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.backgroundColor = [UIColor backgroundColor];
        _scrollView.delegate = self;
        _scrollView.pagingEnabled = YES;
    }
    return _scrollView;
}

- (UIView *)tableHeaderView {
    if (!_tableHeaderView) {
        _tableHeaderView = [[UIView alloc] init];
    }
    return _tableHeaderView;
}

- (UIWebView *)webView {
    if (!_webView) {
        _webView = [[UIWebView alloc] init];
        _webView.delegate = self;
        _webView.scalesPageToFit = YES;
    }
    return _webView;
}

- (UITableView *)detailTableView {
    if (!_detailTableView) {
        _detailTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _detailTableView.backgroundColor = [UIColor backgroundColor];
        _detailTableView.delegate = self;
        _detailTableView.dataSource = self;
        [_detailTableView clearExtendCellLine];
        _detailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_detailTableView registerNib:[UINib nibWithNibName:@"GoodCommentCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"commentCell"];
    }
    return _detailTableView;
}

- (UITableView *)commenTableView {
    if (!_commenTableView) {
        _commenTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        [_commenTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        _commenTableView.backgroundColor = [UIColor backgroundColor];
        _commenTableView.dataSource = self;
        _commenTableView.delegate = self;
        _commenTableView.emptyDataSetSource = self;
        _commenTableView.emptyDataSetDelegate = self;
        [_commenTableView registerNib:[UINib nibWithNibName:@"GoodCommentCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"commentCell"];
        [_commenTableView clearExtendCellLine];
        
        UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
        [header setBackgroundColor:[UIColor backgroundColor]];
        [_commenTableView setTableHeaderView:header];
    }
    return _commenTableView;
}

- (GoodsFlashSaleHeadView *)flashSaleHeadView {
    if (!_flashSaleHeadView) {
        _flashSaleHeadView = [[GoodsFlashSaleHeadView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
    }
    return _flashSaleHeadView;
}

- (NSMutableArray<CouponModel *> *)couponArray {
    if (!_couponArray) {
        _couponArray = [[NSMutableArray alloc] init];
    }
    return _couponArray;
}
- (NSMutableArray<PromotionModel *> *)promotionArray {
    if (!_promotionArray) {
        _promotionArray = [[NSMutableArray alloc] init];
    }
    return _promotionArray;
}
@end
